import React, { Component } from 'react';
import { connect } from 'react-redux';
import { messages, queryCurrencyPrecision } from 'share/common';
import settlementCostService from 'containers/financial-management/settlement-cost/settlement-cost.service';
import AdvancedTable from 'components/advanced-table'
import { Popover } from "antd";
import NewExpense from "containers/my-account/new-expense";
import SlideFrame from "components/slide-frame";

class SettlementCost extends Component {

  state = {
    nowExpense: {},
    showExpenseFlag: false
  };

  searchForm = [{
    id: 'expenseTypeIds', label: '费用类型', component: 'Searcher',
    dataIndex: 'expenseTypeName',
    props: {
      placeholder: '请选择',
      searcherItem: {
        url: '/api/expense/type/company/all/icons',
        title: '选择费用类型',
        key: 'id'
      },
      labelKey: 'name',
      showDetail: true
    },
    parser: value => ({
      expenseTypeIds: value ? value.map(item => item.id) : null
    })
  }];

  columns = [{
    title: messages('common.expense.type')/*费用类型*/,
    dataIndex: 'expenseTypeName',
    render: expenseTypeName => <Popover content={expenseTypeName}>{expenseTypeName}</Popover>
  }, {
    title: messages('common.date')/*日期*/,
    dataIndex: 'createdDate',
    render: createdDate => new Date(createdDate).format('yyyy-MM-dd'),
  }, {
    title: messages('common.accountIncident')/*事由说明*/,
    dataIndex: 'comment',
    render: comment => <Popover content={comment}>{comment || '-'}</Popover>
  }, {
    title: messages('common.attachments')/*附件*/,
    dataIndex: 'attachments',
    render: attachments => attachments.length
  }, {
    title: messages('common.currency')/*币种*/,
    dataIndex: 'invoiceCurrencyCode',
  }, {
    title: messages('common.amount')/*金额*/,
    dataIndex: 'amount',
    align: 'right',
    render: (value, item) => this.filterMoney(value, queryCurrencyPrecision(item.invoiceCurrencyCode)),
  }, {
    title: messages('common.base.currency.amount')/*本位币金额*/,
    align: 'right',
    dataIndex: 'baseAmount',
    render: value => this.filterMoney(value, queryCurrencyPrecision('')),
  }, {
    title: messages('my-account.key170')/*摘要信息*/,
    dataIndex: 'summaryInfo',
    render: value => value ?
      <Popover content={value} placement="topLeft" overlayStyle={{ maxWidth: 350 }}>{value}</Popover> :
      '-'
  }, {
    title: messages('my-account.key171')/*费用归属人*/,
    dataIndex: 'owner',
    render: (value, record) => {
      let showValue = value && value.fullName;
      if (
        showValue &&
        record.reimbursementUserOID &&
        record.ownerOID &&
        record.reimbursementUserOID !== record.ownerOID
      ) {
        showValue += `（${messages('my-account.key232')/*已转交*/}：${record.reimbursementUserName}）`;
      }
      return showValue ? <Popover content={showValue}>{showValue}</Popover> : '-';
    }
  }];

  service = (page, pageSize, searchParams) => {
    const { companyId } = this.props.company;
    const { expenseTypeIds } = searchParams;
    const params = { companyId, expenseTypeIds, page, pageSize };
    return settlementCostService.getSettlementCosts(params)
      .then(res => {
        res.data.rows.forEach(item => {
          item.readonly = true;
        });
        return res;
      })
  };

  renderExpandedRow = (type, content, index) => {
    return (
      <div
        key={index}
        className={`${type.level === 'WARN' ? 
            'warning-expanded-row' : 
            (type.level === 'ERROR' ? 'error-expand-row' : '')}`
        }
      >
        <span>{type.name}</span>
        {type.toast && <span>:{type.toast}</span>}
      </div>
    )
  };

  renderExpandedSpan = (type, content, index) => <span key={index}>{type.name}/</span>;

  renderAllExpandedRow = record => {
    let result = [];
    let infoRes = [];
    let types = record.invoiceLabels || [];
    let lastIndex = -1;
    types.map((label, index) => {
      if (label.level !== 'INFO') {
        result.push(this.renderExpandedRow(label, '', index));
      } else {
        lastIndex = label.name;
        infoRes.push(this.renderExpandedSpan(label, '', index));
      }
    });
    let infoLength = infoRes.length;
    infoLength > 0 && (infoRes[infoLength - 1] = <span key="lastIndex">{lastIndex}</span>);
    result.push(infoRes);
    return result.length > 0 ? result : null;
  };

  render() {
    const { showExpenseFlag, nowExpense } = this.state;
    const { user } = this.props;
    return (
      <div className="full-height-page">
        <AdvancedTable
          index
          title={messages('menu.settlement-cost')/*结算费用*/}
          searchForm={this.searchForm}
          columns={this.columns}
          service={this.service}
          rowKey='invoiceOID'
          expandedRowRender={this.renderAllExpandedRow}
          onRow={record => ({
            onClick: () => (
              this.setState({
                showExpenseFlag: true,
                nowExpense: record
              })
            )
          })}
        />
        <SlideFrame
          show={showExpenseFlag}
          title={messages('financial-management.key800')/*结算费用详情*/}
          content={NewExpense}
          hasFooter={false}
          params={{
            nowExpense,
            slideFrameShowFlag: showExpenseFlag,
            user,
            hasInit: false,
            receiptOperateScene: 3,
            readOnly: true
          }}
          onClose={() => this.setState({
            showExpenseFlag: false,
            nowExpense: null
          })}
          width={800}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
  };
}

export default connect(mapStateToProps)(SettlementCost);
